import queue
import signal
import sys
import threading
import time
from datetime import datetime

import act.seeker as se
import act.trigger as trigger
import act.tools as tools
import act.message as msg
import dataDeal.stringUtils as su
import config
from dto.parse_args import ParseArgs
from threadService import parse_bank_offer_and_save, parse_and_save, parse_ratio_and_save

# 系统生成的询价问题
inquiry_question = ('早上好，今日询价以下币种\n'
                    'USD: 隔夜 7 14 36 92 188 366\n'
                    'RMB: 7 31 180\n'
                    'HKD: 1 21 30\n')
# 处理文件落磁盘的队列
q = queue.Queue()

processor_thread = threading.Thread(target=parse_and_save, args=(q,))
processor_thread.start()


def signal_handler(sig, frame):
    print('收到终止信号，向队列中放入None')
    q.put(None)
    print('主线程退出')
    sys.exit(0)


if __name__ == '__main__':
    # 注册信号处理函数，接收键盘停止主程序
    signal.signal(signal.SIGTERM, signal_handler)
    weChat_window = se.get_window()
    sessions = se.get_chat_list_panel(weChat_window)
    chat_list = sessions.GetChildren()
    # 每次处在文件传输助手对话框，使得其他对话框能接收到消息通知
    file_assistant_button = None
    for session in chat_list:
        if session.Name == "文件传输助手已置顶":
            file_assistant_button = session.GetChildren()[0].GetChildren()[0]
            break
    tools.init_session(sessions, file_assistant_button)
    try:
        while True:
            file_assistant_button.Click()
            time.sleep(3)
            chat_list = sessions.GetChildren()
            for chat_shot in chat_list:
                # 判断是否有消息通知，有则获得消息通知数
                tup = trigger.is_notify_with_text(chat_shot)
                if tup[0]:
                    button = tools.find_control_with_control_type(chat_shot, "ButtonControl")
                    name = button.Name
                    if name in config.name_include:
                        # 根据消息通知数获取消息
                        button.Click()
                        last_msgs = []
                        messageControl = weChat_window.ListControl(Name='消息')
                        msg.get_last_messages(last_msgs, weChat_window, messageControl, int(tup[1]))
                        last_msgs_reverse_list = last_msgs[::-1]
                        for last_msg in last_msgs_reverse_list:
                            print(f"来自-{name}-的消息：{last_msg}")
                            last_msg_upper = last_msg.upper()  # 转换为大写，统一处理
                            contain_keywords = False
                            for keyword in config.keywords:
                                contain_keywords = su.is_in(last_msg_upper, keyword)
                                if contain_keywords:
                                    break
                            if contain_keywords:
                                '''
                                *这里调用一次gpt，目的是为了还价，根据具体情况来
                                注意：还价必须保留对话历史，否则失去上下文无法进行有效报价
                                '''

                                '''
                                以下部分通过另一个线程处理
                                '''
                                # 每个回复时间精确到六位数的微秒级别，避免了主键一致的问题
                                time_shot = datetime.now().strftime("%H:%M:%S.%f")
                                Parse_args_inst = ParseArgs(inquiry_question, last_msg, name, time_shot)
                                q.put(Parse_args_inst)
    except KeyboardInterrupt:
        signal_handler(None, None)
